package mylogger

import (
	"io"
	"os"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// MyLogger 全局log变量
var MyLogger = logrus.New()

func init() {
	pwd, _ := os.Getwd()
	fileName := path.Join(pwd, "LanFileTransmitter.log")
	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		logrus.Infof("init log file error: %v", err)
	}

	MyLogger.Out = io.MultiWriter(os.Stdout, src)
	MyLogger.SetLevel(logrus.DebugLevel)
	MyLogger.SetFormatter(&logrus.TextFormatter{})
}

// LoggerForGin 记录日志到文件的gin中间件
func LoggerForGin() gin.HandlerFunc {
	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		endTime := time.Now()
		latencyTime := endTime.Sub(startTime)
		reqMethod := c.Request.Method
		reqURI := c.Request.RequestURI
		statusCode := c.Writer.Status()
		clientIP := c.ClientIP()

		MyLogger.Infof("| %3d | %13v | %15s | %s | %s |",
			statusCode,
			latencyTime,
			clientIP,
			reqMethod,
			reqURI,
		)
	}
}
